package filter;

import jakarta.servlet.*;
import jakarta.servlet.annotation.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;

@WebFilter(filterName = "CheckFilter")
public class CheckFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpSession session = ((HttpServletRequest) request).getSession();
        // 获取session中的Username信息
        String username = (String) session.getAttribute("Username");
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        // 正则匹配login相关页面（login.jsp和login_deal.jsp
        boolean isLoginPath = httpServletRequest.getServletPath().matches(".*login.*");
        // 正则匹配UserServlet
        boolean isUserServlet = httpServletRequest.getServletPath().matches(".*UserServlet.*");
        // 正则匹配reg相关页面（reg.jsp和reg_deal.jsp）
        boolean isRegPath = httpServletRequest.getServletPath().matches(".*reg.*");
        // 正则匹配消息处理页面（message.jsp）
        boolean isMessage = httpServletRequest.getServletPath().matches(".*message.*");
        // 正则匹配图片相关内容（img）
        boolean isImg = httpServletRequest.getServletPath().matches(".*img.*");
        // 判断是否为登录状态以及是否为白名单页面
        if (username != null || isLoginPath || isUserServlet || isRegPath || isMessage || isImg) {
            if (username == null) {
                System.out.println("您尚未登录");
            } else {
                System.out.println("您已成功登录，用户名：" + username);
            }
            chain.doFilter(request, response);
        } else {
            ((HttpServletResponse) response).sendRedirect("login.jsp");
        }
    }
}
